package com.emm.yixun.mobile.ui.web.helper

import android.content.Context
import android.util.Log
import com.alibaba.fastjson.JSONObject
import com.emm.yixun.mobile.application.EmmApplication
import com.emm.yixun.mobile.model.DistributionConsultant
import com.emm.yixun.mobile.model.GetConsultantList
import com.emm.yixun.mobile.ui.web.Util
import com.emm.yixun.mobile.ui.web.bean.CustomerDetail
import com.loopj.android.http.AsyncHttpClient
import com.loopj.android.http.AsyncHttpResponseHandler
import com.loopj.android.http.RequestParams
import xf.tools.Loading

object HttpHelper {

    private const val TAG = "HttpHelper"

    fun getConsultantList(context: Context, onSuccess: (consultants: List<GetConsultantList.ConsultantList>) -> Unit) {
        val callback = object : RequestCallback<GetConsultantList> {
            override fun onResult(result: GetConsultantList) {
                if ("1" == result.result) {
                    Log.v(TAG, "获取成功")
                    if (result.consultantList.isNotEmpty()) {
                        onSuccess(result.consultantList)
                    } else {
                        EmmApplication.T("当前没有置业顾问")
                    }
                } else {
                    try {
                        EmmApplication.T(result.errorMsg.toString())
                        Log.v(TAG, "errorCode:" + result.errorCode.toString() + "errorMsg:"
                            + result.errorMsg.toString())
                    } catch (e: NullPointerException) {
                        Log.v(TAG, "错误信息获取空指针异常")
                    }
                }
            }
        }

        request(context, "getConsultantList", mapOf(), GetConsultantList::class.java, callback)
    }

    fun distributionConsultant(context: Context, consultantId: String, customerId: String) {
        val params = mapOf(
            "consultantUserId" to consultantId,
            "customerList" to listOf(CustomerDetail(customerId))
        )

        val callback = object : RequestCallback<DistributionConsultant> {
            override fun onResult(result: DistributionConsultant) {
                if ("1" == result.result) {
                    EmmApplication.T("分配成功")
                } else {
                    try {
                        EmmApplication.T(result.errorMsg.toString())
                        Log.v(TAG, "errorCode:" + result.errorCode.toString() + "errorMsg:"
                            + result.errorMsg.toString())
                    } catch (e: NullPointerException) {
                        Log.v(TAG, "错误信息获取空指针异常")
                    }
                }
            }
        }

        request(context, "distributionConsultant", params, DistributionConsultant::class.java, callback)
    }

    private fun <T : Any> request(
        context: Context,
        method: String,
        params: Map<String, Any> = mapOf(),
        clazz: Class<T>,
        callback: RequestCallback<T>
    ) {

        val paramsMap = java.util.HashMap<String, Any>()
        paramsMap["params"] = mutableMapOf<String, Any>().apply {
            putAll(params)
            putAll(Util.getCommonParam())
        }
        val json = JSONObject(paramsMap)
        val requestParams = RequestParams()
        requestParams.put("body", json.toString())

        EmmApplication.updateUrl(method)

        Log.v(TAG, "Http request: " + EmmApplication.urlStr + "?body=" + json.toString())

        val asyncHttpClient = AsyncHttpClient()

        asyncHttpClient.post(EmmApplication.urlStr, requestParams, object : AsyncHttpResponseHandler() {
            override fun onFailure(error: Throwable, content: String?) {
                super.onFailure(error, content)
                Loading.hideDialogForLoading()
                Log.v(TAG, "请求结束error:$error==$content")
            }

            override fun onFinish() {
                super.onFinish()
                Log.v(TAG, "请求结束")
                Loading.hideDialogForLoading()
            }

            override fun onStart() {
                super.onStart()
                Log.v(TAG, "请求开始")
                Loading.showDialogForLoading(context, "正在加载...", false, true, 60000)
            }

            override fun onSuccess(content: String?) {
                super.onSuccess(content)
                if (content == null) {
                    return
                }

                val jsonObj = JSONObject.parseObject(content)
                val resData = jsonObj["resData"] as JSONObject?

                if (resData == null) {
                    Log.v(TAG, "信息返回值为空")
                    return
                }

                val distribution = JSONObject.parseObject(resData.toString(), clazz)

                callback.onResult(distribution)
            }
        })
    }

}

interface RequestCallback<T : Any> {
    fun onResult(result: T)
}